// 引入 lodash 库，用于数据处理和操作
const _ = require('lodash')
// 引入 path 模块，用于处理文件和目录路径
const path = require('path')
// 引入 esm 库，用于在 Node.js 中支持 ES6 模块
const esm = require('esm')
// 使用 esm 配置来加载模块
const requireModule = esm(module)

// 获取项目根目录
const ROOT_DIR = path.join(__dirname, '..')
// helpers   目录
const HELPERS_DIR = path.join(ROOT_DIR, 'helpers')
// front src 目录
const FRONT_SRC_DIR = path.join(ROOT_DIR, 'src')
// server data 目录
const SERVER_DATA_DIR = path.join(ROOT_DIR, 'server/data')

// 加载 FOLDER_OPTIONS 常量
const { FOLDER_OPTIONS } = requireModule(path.join(FRONT_SRC_DIR, 'utils/modules/constant.js'))

// 读取 server 的 json 文件
const { readServerJsonFiles } = requireModule(path.join(HELPERS_DIR, 'readServerJson.js'))
// 读取并构建 fixedGroupMapObject
const fixedGroupMapObject = FOLDER_OPTIONS.reduce((acc, folder) => {
  const groupModulePath = path.join(FRONT_SRC_DIR, 'utils', 'modules', 'groups', `${folder}.js`)
  const { [`${folder.toUpperCase()}_GROUP_MAP`]: groupMap } = requireModule(groupModulePath)
  acc[folder] = groupMap
  return acc
}, {})

const groupTypes = ['sixteen']
// const groupTypes = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'ten', 'twelve', 'sixteen', 'twentyfour']
// const groupTypes = ['two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'ten', 'twelve', 'sixteen']

// 读取并构建 randomGroupMapObject
const randomGroupMapObject = FOLDER_OPTIONS.reduce((acc, folder) => {
  const jsonData = readServerJsonFiles(SERVER_DATA_DIR, folder)
  if (groupTypes.includes(folder)) {
    acc[folder] = jsonData
  }
  return acc
}, {})

// 最终的分组
const finalGroupMap = _.merge({}, fixedGroupMapObject, randomGroupMapObject)
// const finalGroupMap = _.merge({}, fixedGroupMapObject)

// 创建铺平的分组对象和数组对象
const { flatGroupMap, groupArray } = Object.keys(finalGroupMap).reduce(
  (acc, groupType) => {
    if (groupTypes.includes(groupType)) {
      const groupMap = finalGroupMap[groupType]

      Object.keys(groupMap).forEach((groupName) => {
        // 填充平铺对象
        acc.flatGroupMap[groupName] = groupMap[groupName]

        // 填充数组对象
        acc.groupArray.push({
          group_name: groupName,
          group_type: groupType,
          group_data: groupMap[groupName]
        })
      })
    }
    return acc
  },
  { flatGroupMap: {}, groupArray: [] }
)

module.exports = { finalGroupMap, flatGroupMap, groupArray }
